import { Component } from '@angular/core';
import { NavController, AlertController, Nav } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';
import { environment } from "../../services/environment";
import { LoginPage } from "../login/login";

@Component({
  selector: 'page-user',
  templateUrl: 'signup.html'
})
export class SignupPage {
  // 用户ID
  public userId: any;
  // 登录密码
  public passWord: any;
  // 原密码
  public originPassWord: any;
  // 新密码
  public newPassWord1: any;
  public newPassWord2: any;

  constructor(
    public http: Http,
    public storage: Storage,
    public nav: Nav,
    public navCtrl: NavController,
    public alert: AlertController
  ) {
    let that = this;
    // 获取用户ID
    that.storage.get('UserId').then(UserId => {
      that.userId = UserId;
    })
    // 获取登录密码
    that.storage.get('PassWord').then(PassWord => {
      that.passWord = PassWord;
    })
  }

  // 修改密码
  setPassword() {
    let that = this;
    if (this.checkOriginPassWord()) {
      if (this.checkNewPassWord()) {
        let postBody: any = {
          where: {
            UserId: this.userId
          },
          values: {
            PassWord: this.newPassWord2
          }
        }
        this.http.post(environment.server + 'api/v1/users/edit', postBody).map(res => res.json()).subscribe(body => {
          if (body.isSuccess == true) {
            that.storage.remove('token');
            that.storage.remove('Role');
            that.storage.remove('UserId');
            that.storage.remove('PassWord');
            that.storage.remove('UserName');
            that.storage.remove('updatedAt');
            that.nav.setRoot(LoginPage);
          }
        })
      } else {
        this.errorAlert('新密码不一致');
      }
    } else {
      this.errorAlert('原密码不正确');
    }
  }
  // 判断原密码是否正确
  checkOriginPassWord() {
    if (this.originPassWord === this.passWord) {
      return true;
    } else {
      return false;
    }
  }
  // 判断新密码是否正确
  checkNewPassWord() {
    if (this.newPassWord1 === this.newPassWord2) {
      return true;
    } else {
      return false;
    }
  }
  // 弹窗
  errorAlert(tips: any) {
    let alert = this.alert.create({
      title: '提示',
      subTitle: tips,
      buttons: ['ok']
    });
    alert.present();
  }
}
